﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;

namespace GS.Cricket.Service.Impl.NHibernate
{
    public static class Extensions
    {

        public static object Add<T>(this object o)
        {
            using (ISession session = NHibernateHelper<T>.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    var result = session.Save(o);
                    transaction.Commit();
                    return result;
                }
            }
        }

        public static void Update<T>(this object o)
        {
            using (ISession session = NHibernateHelper<T>.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Update(o);
                    transaction.Commit();
                }
            }
        }

        public static void Delete<T>(this object o)
        {
            using (ISession session = NHibernateHelper<T>.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(o);
                    transaction.Commit();
                }
            }
        }

        public static object GetByName<T>(this string name)
        {
            using (ISession session = NHibernateHelper<T>.OpenSession())
            {
                var result = session
                    .CreateCriteria(typeof(T))
                    .Add(Restrictions.Eq("Name", name))
                    .UniqueResult<T>();
                return result;
            }
        }

        public static object GetById<T>(this object ID)
        {
            using (ISession session = NHibernateHelper<T>.OpenSession())
            {
                return session.Get<T>(ID);
            }
        }

        public static IEnumerable<T> GetAll<T>(this object o)
        {
            using (ISession session = NHibernateHelper<T>.OpenSession())
            {
                var result = session
                    .CreateCriteria(typeof(T))
                    .List<T>();
                return result;
            }
        }

    }
}
